package com.xltt.watchclient;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.xltt.watchclient.model.ButtonInfo;
import com.xltt.watchclient.module.bean.OptResult;
import com.xltt.watchclient.module.service.BleController;
import com.xltt.watchclient.module.service.ConnectServer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import static com.xltt.watchclient.module.Consts.CLIENT_CONNECT;
import static com.xltt.watchclient.module.Consts.CLIENT_CONNECTED;
import static com.xltt.watchclient.module.Consts.CLIENT_DISCONNECT;
import static com.xltt.watchclient.module.Consts.CLIENT_START;
import static com.xltt.watchclient.module.service.BleController.CONNECT_STATE;
import static com.xltt.watchclient.module.service.BleController.GET_CONNECTED_DEVICES;
import static com.xltt.watchclient.module.service.BleController.START_DEVICE;


public class MainFragment extends Fragment {
    private static final int SCAN_DEVICE = 1;
    private static final int ACTIVE_DEVICE = 2;
    private static final int CONNECT_DEVICE = 3;
    private static final int RECONNECT_DEVICE = 4;
    private static final int PAIR_DEVICE = 5;
    private static final int PUSH_DEVICE = 6;
    private static final int OPEN_LISTENT_NOTITY = 7;
    private static final int CHECK_DEVICE = 8;

    List<ButtonInfo> list = new ArrayList<>();

    {
        list.add(new ButtonInfo(OPEN_LISTENT_NOTITY, "打开通知监听开关"));
        list.add(new ButtonInfo(SCAN_DEVICE, "扫描设备"));

    }

    View prgLayout;

    private void setupLoading(View view) {
        prgLayout = view.findViewById(R.id.prgLayout);
    }

    public void showLoading() {
        prgLayout.setVisibility(View.VISIBLE);
    }

    public void hideLoading() {
        prgLayout.setVisibility(View.GONE);
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_main, container, false);
    }

    NavController nNavController;
    ConnectServer mConnectServer;

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        requireActivity().setTitle("主菜单");
        setupLoading(view);

        nNavController = Navigation.findNavController(view);
        mRecyclerView = view.findViewById(R.id.btnList);
        mRecyclerView.setLayoutManager(new GridLayoutManager(requireContext(), 1, LinearLayoutManager.VERTICAL, false));
        mQuickAdapter = new QuickAdapter(R.layout.item_button_view, list);
        mRecyclerView.setAdapter(mQuickAdapter);

        mQuickAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                ButtonInfo mButtonInfo = list.get(position);
                switch (mButtonInfo.key) {
                    case SCAN_DEVICE: {
                        nNavController.navigate(R.id.acion_main_to_scan);
                        break;
                    }
                    case OPEN_LISTENT_NOTITY: {
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                            Intent intent = new Intent(
                                    "android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
                            startActivity(intent);
                        } else {
                            Toast.makeText(getActivity(), "手机的系统不支持此功能", Toast.LENGTH_SHORT).show();
                        }
                        break;
                    }
                    case CONNECT_DEVICE: {

                        new AlertDialog.Builder(requireContext())
                                .setTitle("确认连接当前设备为：" + address)
                                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        dialog.dismiss();
                                    }
                                }).setPositiveButton("连接", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                showLoading();
                                LogTool.d("开始连接");
                                ((MainActivity) requireActivity()).tryConnect(address);
                            }
                        }).create().show();

                        break;
                    }
                    case ACTIVE_DEVICE: {
                        ((MainActivity) requireActivity()).activeDevice("liwang111", "hahahahahahahahahahahahahaha");
                        break;
                    }
                    case CHECK_DEVICE: {
                        ((MainActivity) requireActivity()).checkState();

                        break;
                    }
                }
            }
        });


        if (nNavController.getPreviousBackStackEntry() != null) {
            nNavController.getCurrentBackStackEntry()
                    .getSavedStateHandle().getLiveData("device")
                    .observe(getViewLifecycleOwner(), new Observer() {
                        @Override
                        public void onChanged(Object o) {
                            address = (String) o;
                            LogTool.d("" + address);
                            list.clear();
                            list.add(new ButtonInfo(CONNECT_DEVICE, "连接"));
                            mQuickAdapter.notifyDataSetChanged();
                        }
                    });
        }
    }


    String address;

    RecyclerView mRecyclerView;
    QuickAdapter mQuickAdapter;

    class QuickAdapter extends BaseQuickAdapter<ButtonInfo, BaseViewHolder> {

        public QuickAdapter(int layoutResId, @Nullable List<ButtonInfo> data) {
            super(layoutResId, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, ButtonInfo item) {
            helper.setText(R.id.item_title, item.name);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = false, priority = 0)
    public void onResult(OptResult message) {
        LogTool.d(message.type+"");
        switch (message.type) {
            case START_DEVICE: {
                if (!message.isSuccess) {
                    Toast.makeText(requireContext(), "连接失败", Toast.LENGTH_SHORT).show();
                }
                break;
            }
            case GET_CONNECTED_DEVICES: {

                if (TextUtils.isEmpty(message.getDeviceName())) {
                    Toast.makeText(requireContext(), "未连接：", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(requireContext(), "已连接", Toast.LENGTH_SHORT).show();
                }

                break;
            }
            case BleController.ACTIVE_DEVICE: {
                if (message.isSuccess) {
                    Toast.makeText(requireContext(), "激活成功", Toast.LENGTH_SHORT).show();
                }else{
                    Toast.makeText(requireContext(), "激活失败", Toast.LENGTH_SHORT).show();
                }
                break;
            }
            case CONNECT_STATE: {
                if (message.isSuccess) {
                    switch (message.code) {
                        case CLIENT_START: {
                            showLoading();
                            Toast.makeText(requireContext(), "开始连接", Toast.LENGTH_SHORT).show();
                            break;
                        }
                        case CLIENT_CONNECT: {
                            Toast.makeText(requireContext(), "连接中", Toast.LENGTH_SHORT).show();
                            break;
                        }
                        case CLIENT_DISCONNECT: {
                            hideLoading();
                            Toast.makeText(requireContext(), "断开连接", Toast.LENGTH_SHORT).show();
                            list.clear();
                            list.add(new ButtonInfo(OPEN_LISTENT_NOTITY, "打开通知监听开关"));
                            list.add(new ButtonInfo(SCAN_DEVICE, "扫描设备"));
                            mQuickAdapter.notifyDataSetChanged();
                            break;
                        }
                        case CLIENT_CONNECTED: {
                            hideLoading();
                            Toast.makeText(requireContext(), "连接完成", Toast.LENGTH_SHORT).show();
                            list.clear();
                            list.add(new ButtonInfo(ACTIVE_DEVICE, "激活"));
                            list.add(new ButtonInfo(SCAN_DEVICE, "重连"));
                            list.add(new ButtonInfo(CHECK_DEVICE, "查看连接状态"));
                            mQuickAdapter.notifyDataSetChanged();
                            break;
                        }
                    }

                }
                break;
            }

        }

    }

    @Override
    public void onResume() {
        super.onResume();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }
}
